package com.gdufs.secondhandwebsite.controller;

import com.gdufs.secondhandwebsite.service.ex.*;
import com.gdufs.secondhandwebsite.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;


public class BaseController {
    /** 操作成功的状态码 */
    public static final int OK = 200;

    // 异常统一拦截到此方法中，这个方法就是请求处理方法，方法的返回值直接发给前端
    @ExceptionHandler({ServiceException.class})
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicatedException) {
            result.setState(4000);
            result.setMessage("用户名已经被占用");
        }else if (e instanceof UserNotFoundException) {
            result.setState(4001);
            result.setMessage(e.getMessage());
        }else if (e instanceof PasswordNotMatchException) {
            result.setState(4002);
            result.setMessage(e.getMessage());
        }else if(e instanceof InsertException) {
            result.setState(5000);
            result.setMessage("注册时产生未知的异常");
        } else if (e instanceof UpdateException) {
            result.setState(5001);
        }
        return result;
    }
    // 方便后续获取
    /**
     * 从HttpSession对象中获取uid
     * @param session HttpSession对象
     * @return 当前登录的用户的id
     */
    protected final Integer
    getUidFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /**
     * 从HttpSession对象中获取用户名
     * @param session HttpSession对象
     * @return 当前登录的用户名
     */
    protected final String
    getUsernameFromSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }

    protected final String
    getUserImgFromSession(HttpSession session) {
        return session.getAttribute("userImg").toString();
    }
}
